"""
@File    : logger.py
@Author  : ixiaodu
@Date    : 2024/5/23
@Desc    ：日志管理模块
"""

import logging
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
import colorlog

from config.config import cm
# 启用ANSI颜色支持（仅限Windows）
import sys

if sys.platform.startswith('win'):
    import colorama

    colorama.init()


class Log:
    def __init__(self, seg):
        self.seg = seg

        # 创建logger
        self.logger = logging.getLogger(__name__)
        self.logger.handlers.clear()  # 清除已有处理器
        self.logger.setLevel(logging.INFO)  # 统一日志级别

        # 定义日志文件大小为10M
        max_bytes = 10 * 1024 * 1024
        # 定义保留的文件数量为50个
        backup_count = 50

        # 创建日志文件处理器
        if self.seg == "time":
            fh = TimedRotatingFileHandler(cm.log_file, when='D', backupCount=backup_count, encoding='utf-8')
            fh.setLevel(logging.INFO)
        else:
            fh = RotatingFileHandler(cm.log_file, maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8')
            fh.setLevel(logging.INFO)

        # 创建一个handle输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)

        # 设置日志格式
        file_formatter = logging.Formatter('%(levelname)s\t%(asctime)s\t[%(filename)s:%(lineno)d]\t%(message)s')
        console_formatter = self.get_formatter()

        fh.setFormatter(file_formatter)
        ch.setFormatter(console_formatter)

        # 添加到handle
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)

    def get_formatter(self):
        fmt = '%(log_color)s%(levelname)s\t%(asctime)s\t[%(filename)s:%(lineno)d]\t%(message)s%(reset)s'
        return colorlog.ColoredFormatter(fmt, log_colors={
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red',
        })


# 使用大小分割log文件
log = Log('size').logger

if __name__ == '__main__':
    # 测试日志输出
    log.debug("This is a debug message")
    log.info("This is an info message")
    log.warning("This is a warning message")
    log.error("This is an error message")
    log.critical("This is a critical message")
